<?php

namespace Manager;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 评论管理编辑管理基类
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Comment extends Comments
{
    /**
     * 增加评论
     *
     * @access public
     * @param array $values 评论结构数组
     * @return integer
     */
    public function addComment(array $values)
    {
		$values['type'] = 'comment';
		
        /** 插入数据 */
        $insertId = $this->addComments($values);
			
        if ($insertId > 0) {

            /** 更新评论数 */
		    if(!empty($values['cid']) && 'approved' == $values['status']){
				$this->widget('Manager\Contents')->incr( $values['cid'], 'commentsNum' );
			}
		}

		return $insertId;
    }

    /**
     * 更新评论
     *
     * @access public
     * @param int $coid 评论coid
     * @param array $values 评论结构数组
     * @return integer
     */
    public function updateComment($coid, array $values)
    {
        $comment = $this->db
			->select('table.comments.cid', 'table.comments.status')
		    ->from('table.comments')
            ->where('table.comments.coid = ? AND table.comments.type = ?', $coid, 'comment')
            ->limit(1)
		    ->fetch();
		
        if (empty($comment))
			
			return ;
		
		$values['type'] = 'comment';
		
        /** 更新数据 */
        $updateRows = $this->updateComments($coid, $values);
		
        /** 更新评论数 */
		if($updateRows && isset($values['status']) && 'approved' != $comment['status'] && 'approved' == $values['status']){
			$this->widget('Manager\Contents')->incr( $comment['cid'], 'commentsNum' );
		}
		
        /** 更新评论数 */
		if($updateRows && isset($values['status']) && 'approved' == $comment['status'] && 'approved' != $values['status']){
			$this->widget('Manager\Contents')->decr( $comment['cid'], 'commentsNum' );
		}
		
		return $updateRows;
    }

    /**
     * 删除数据
     *
     * @access public
     * @param int $coid 评论coid
     * @return integer
     */
    public function deleteComment($coid)
    {
        $deleteRows = false;
		
        $comment = $this->db
			->select('table.comments.cid', 'table.comments.status')
		    ->from('table.comments')
            ->where('table.comments.coid = ? AND table.comments.type = ?', $coid, 'comment')
            ->limit(1)
		    ->fetch();

        if (empty($comment))
			
			return ;

        /** 更新评论数 */
		if('approved' == $comment['status']){
			
			$this->widget('Manager\Contents')->decr( $comment['cid'], 'commentsNum' );
		}

        /** 删除评论 */    
        $deleteRows = $this->deleteComments($coid);
        
		return $deleteRows;
    }
}

